<template>
<view>
  <!--顶部导航-->
  <view class="nav_top">
    <view class="nav_content">
      <image class="nav_image" src="../../static/AI/logo.png" mode="widthFix"></image>
      <view class="nav_text">
        <text>三七AI助手</text>
        <text>你的智能助手，帮你获取知识</text>
      </view>
    </view>
  </view>
  <!--占位高度-->
  <view :style="{height:'90rpx'}"></view>
  <!--页面默认文本-->
  <view class="Sent_information backdrop your-element" v-if="messageData.length<=0">{{greet}}</view>
  <view class="Sent_information backdrop widthAuto your-element" v-if="messageData.length<=0">
    <view class="nav_content problem_top">
      <image src="../../static/AI/wen.png" mode="widthFix"></image>
      <text>你可以这样问我</text>
    </view>
    <view class="Default_problem" v-for="(item,index) in problemList" :key="index" @click="selectText(item)">
      {{item}}
    </view>
  </view>
  <!--用户和AI对话-->
<!--用户-->
<block v-for="(item,index) in messageData" :key="index">
<view class="user-backdrop" v-if="item.role == 'user'">
  <view><image src="../../static/tabs/user-active.png" mode="widthFix"></image></view>
  <view>{{item.content}}</view>
</view>
<!--AI回复-->
<view class="Sent_information backdrop" v-else>
  <view class="loading" v-if="item.loadShow">
    <view class="loader"></view>
    <view>我正在思考中</view>
  </view>
  <view class="ai_content" v-if="item.content != ''">
    <text user-select>{{item.content}}</text>
    <image v-if="item.copyIcon" @click="copyData(item.content)" src="../../static/AI/copy.png" mode="widthFix"></image>
  </view>
</view>
</block>
<!--底部输入框-->
<view class="Input-field">
  <view><image src="../../static/AI/clean.png" mode="aspectFit" @click="clearMessage"></image></view>
  <input placeholder="请输入你的问题" maxlength="-1" cursor-spacing="40" confirm-type="send" auto-blur v-model="text" @confirm="sendMessage" :disabled="sendIngState"/>
  <view><image src="../../static/AI/send.png" mode="aspectFit" @click="sendMessage"></image></view>
</view>
<view style="height: 400rpx;"></view>
</view>
</template>

<script>
  export default{
    data() {
      return {
        greet:'你好，我是一个了解中国药材的知识的小机器，你可以叫我三七。对于中药材，你想了解什么呢？',
        problemList:[
          '三七是什么药材，有什么作用',
          '江西省生产什么中药材',
          '哪些药材属于清热解毒药'
        ],
        text:'',
        //Socket挂载方法
        SocketTask:'',
        //历史对话
        historyTestList: [],
        //存储AI返回的文本
        sparkResult: '',
        //存储用户和ai对话：临时存储
        messageData: [],
        //发送状态
        sendIngState: false
        
      };
      
    },
    methods:{
      async sendMessage(){
        if(this.text.trim().length > 0){
          this.text = this.text.trim()
        }else{
          wx.showToast({
            title:'请输入询问内容',
            icon:'none'
          })
          return false
        }
        if(this.sendIngState){
          wx.showToast({
            title:'等待AI回复完毕',
            icon:'none'
          })
          return false
          
        }
        
        this.messageData.push({
          "role":"user",
          "content":this.text
        });
        this.messageData.push({
          "role":"assistant",
          "content":'',
          "loadShow":true,
          "copyIcon":false
        });
        this.sparkResult = ''
        console.log(wssUrl);
        this.sendIngState = true
        //连接
        const wssUrl = await wx.cloud .callFunction({name:'gpt-uni'})
         this.SocketTask = uni.connectSocket({
          url:wssUrl.result.url,
          success:res =>{
            console.log(res,'ws连接成功');
          },
          fail:err=>{
            console.log(err,'ws连接失败');
            wx.showToast({title:'出现异常错误',icon:'none'})
            this.messageData = []
            this.sendIngState = false
          }
        });
        //链接失败的监听
        this.SocketTask.onError((res) => {
          console.log('监听到错误',res);
          wx.showToast({title:'出现异常错误',icon:'none'})
          this.messageData = []
          this.sendIngState = false
        });
        //连接打开事件的监听函数
        this.SocketTask.onOpen((data) =>{
          console.log('连接成功，接下来可以发送消息了',data);
          this.historyTestList.push({
            "role": "user",
            "content": this.text
          });
          this.text = '';
          // 需要传的值
          let params = {
            "header": {
              "app_id": wssUrl.result.APPID,
              },
              "parameter": {
                "chat": {
                  "domain": "4.0Ultra",
                  "temperature": 1,
                  },
                  },
                  "payload": {
                    "message": {
                      "text": this.historyTestList,
                      },
                      },
                      };
                      this.SocketTask.send({
                        data:JSON.stringify(params),
                        success:(res)=>{
                          console.log('发送消息成功');
                        },
                        fail:(res) =>{
                          console.log('发送消息失败');
                          wx.showToast({title:'重新异常错误',icon:'none'})
                          this.messageData = []
                          this.sendIngState = false
                        }
                      })
        });
        //调用消息接口
        this.returnMessage();
      },
      //调用消息接口
      returnMessage(){
        this.SocketTask.onMessage((res) =>{
          this.messageData[this.messageData.length -1 ].loadShow = false
          console.log(res);
          const obj = JSON.parse(res.data)
          console.log(obj);
          
          //错误判断
          if(obj.header.code !== 0){
            this.sparkResult += obj.header.message.replace(/↵/g, '\n');
            this.messageData[this.messageData.length - 1].content = this.sparkResult
            this.sendIngState = false
            this.messageData[this.messageData.length - 1].copyIcon = true
            return false
            
          }
          const dataArray = obj.payload.choices.text
          dataArray.forEach((item) =>{
            this.sparkResult += item.content.replace(/↵/g, '\n');
            this.messageData[this.messageData.length - 1].content = this.sparkResult
          })
          //超出页面，自动滚动
          wx.pageScrollTo({
            scrollTop:3000
          })
          //ai全部回复的处理
          if(obj.header.code === 0 && obj.header.status === 2){
            this.historyTestList.push({
              "role":"assistant",
              "content":this.sparkResult
            })
            //打开复制图标
            this.messageData[this.messageData.length -1 ].copyIcon = true
            this.sendIngState = false
          }
        })
      },
      //复制内容
      copyData(val){
        wx.setClipboardData({data:val})
      },
      //清空信息
      clearMessage(){
        if(this.sendIngState){
          wx.showToast({
            title:'等待AI回复完毕',
            icon:'none'
          })
          return false
        }
        this.sparkResult = ''
        this.historyTestList = []
        this.messageData = []
      },
      //默认发送
      selectText(val){
        this.text = val;
        this.sendMessage();
        
      }
    }
  }

</script>

<style>
  .loading{
    display: flex;
    align-items: center;
    
  }
  .Input-field{
    display: flex;
    align-items: center;
    justify-content: space-between;
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    border-top: 1px solid #eee ;
    padding-top: 30rpx;
    padding-bottom: 40rpx;
    background-color: #f6f8fe;
    color: #000000;
  }
  .Input-field input{
    width: 100%;
    background-color: #fff;
    border-radius: 10rpx;
    padding: 20rpx;
  }
  .Input-field view{
    height: 80rpx;
    width: 80rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 0 10rpx;
  }
  .Input-field image{
    height: 50rpx;
    width: 50rpx;
    display: block;
  }
  @keyframes spin {
    0%{ transform: rotate(0deg);}
    100%{ transform: rotate(360deg);}
  }
  .loader{
    border: 5rpx solid #f3f3f3;
    border-top:5rpx solid #3498db;
    border-radius: 50%;
    width: 40rpx;
    height: 40rpx;
    animation: spin 1s linear infinite;
    margin-right:10rpx ;
  }
  .ai_content{
    display: flex;
    flex-direction: column;
  }
  .ai_content text{
    border-bottom: 1px solid #f3f3f4;
    padding-bottom: 10rpx;
    color: #000000;
  }
  .ai_content image{
    width: 40rpx;
    align-self: flex-end;
    margin-top: 10rpx;
  }
  .user-backdrop{
    color: #555d92;
    display: flex;
    margin: 20rpx;
  }
  .user-backdrop image{
    width: 38rpx;
    display: block;
    border-radius: 50%;
  }
  .user-backdrop view:nth-child(1){
    height: 48rpx;
    margin-right: 10rpx;
    display: flex;
    align-items: center;
  }
  .user-backdrop view:nth-child(2){
    line-height: 1.5;
    align-items: center;
  }
  .Sent_information{
    padding: 10rpx;
    margin: 20rpx;
    line-height: 1.5;
    border-radius: 10rpx;
    font-size: 29rpx;
  }
  .backdrop{
    background-color: #fefefe;
  }
  @keyframes fadeInFromTop {
    0%{
      opacity: 0;
      transform: translateY(30rpx);
    }
    100%{
      opacity: 1;
      transform: translateY(0);
    }
  }
  .your-element{
    animation-name: fadeInFromTop;
    animation-duration: 0.7s;
    animation-timing-function: ease-in;
    animation-fill-mode: forwards;
  }
  .widthAuto{
    width: auto;
  }
  .problem_top image{
    width: 50rpx;
    display: block;
    margin-right: 10rpx;
  }
  .problem_top text{
    font-weight: bold;
  }
  .Default_problem{
    border: 1rpx solid #e8f0fc;
    border-radius: 40rpx;
    padding: 15rpx 0;
    text-align: center;
    margin: 20rpx 0;
    color:#000000;
    font-weight: bold;
  }
  .nav_top{
    position: fixed;
    width: 100%;
    height: 90rpx;
    background-color: #a1cc97;
    z-index: 999;
  }
  .nav_image{
    width: 80rpx;
  }
  .nav_content{
    display: flex;
    align-items: center;
  }
  .nav_text{
    display: flex;
    flex-direction: column;
  }
  .nav_text text:nth-child(1){
    font-size: 28rpx;
    font-weight: bold;
  }
  .nav_text text:nth-child(2){
    font-size: 25rpx;
    color:#798189;
  }
</style>